import { ApplicationRef, ComponentFactoryResolver, EmbeddedViewRef, Injectable, Injector } from '@angular/core';
import { NavigationEnd, Router, Event, RouteConfigLoadStart, RouteConfigLoadEnd, NavigationStart, NavigationError } from '@angular/router';
import { Observable } from 'rxjs';
import { filter } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class LoadService {
  // DxLoadPanelComponent
  public loadPanel: any;
  public ajaxLongTimer: number = 1000 * 60 * 3 * 10; // 默认三十分钟 // ajax最长时间
  
  constructor(
    // private factory: ComponentFactoryResolver,
    // private inject: Injector,
    public app: ApplicationRef,
    private router: Router
  ) {
      this.router.events
      .subscribe(
        event => {
          if(event instanceof RouteConfigLoadStart) {
            // 懒加载新的资源时触发
            this.show();
          } else if(event instanceof RouteConfigLoadEnd) {
            // 加载新的资源完毕时触发
            this.hide();
          } else if(event instanceof NavigationStart) {
            // 切换路由时触发
            this.show();
          }
          if(event instanceof NavigationEnd) {
            // 切换路由完毕时触发
            this.hide();
          }
          if(event instanceof NavigationError) {
            // 报错时触发  
            this.hide();
          }
        }
      )
    // this.renderLoadPanel();
  }
  /**
   * 1. 将要使用组件在LoadModule的entryComponents中声明
   * 2. 正常使用即可
   */
  // renderLoadPanel(): Promise<void>{
  //   return new Promise((reslove) => {
  //     const componentFactory = this.factory.resolveComponentFactory(DxLoadPanelComponent);
  //     let comp = componentFactory.create(this.inject);
  //     this.app.attachView(comp.hostView);
  //     // console.log('loadComponent', comp);
  //     this.loadPanel = comp.instance;
  //     document.body.appendChild((comp.hostView as EmbeddedViewRef<{}>).rootNodes[0])
  //     reslove();
  //   })
  // }
  
  public show(text: string = "正在加载", target: string = '.content'){
    this._show(text, target);
  }

  private _show(text: string, target: string) {
    this.loadPanel.message = text;
    this.loadPanel.position = {
      my: 'center',
      at: 'center',
      of: target
    };
    if(this.loadPanel.instance) {
      this.loadPanel.instance.show();
    }
    setTimeout(
      () => {
        this.loadPanel.instance.hide();
      }, this.ajaxLongTimer
    )
  }
  public hide(){
    if(this.loadPanel.instance) {
      this.loadPanel.instance.hide();
    }
  }
}
